﻿using Newtonsoft.Json.Linq;
using System;
using System.Buffers;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using TouchSocket.Core;
using TouchSocket.Sockets;
using YS.Domain.IoT.Receive;

namespace YS.Domain.IoT.Extension
{
    /// <summary>
    ///连接信息扩展
    /// </summary>
    public static class TcpSessionExtension
    {
        private static readonly byte SpMark = 0x24;
        /// <summary>
        ///获取客户端Id
        /// </summary>
        /// <param name="tcpSession"></param>
        /// <returns></returns>
        public static string GetClientId(this ITcpSession tcpSession)
        {
            return ((TcpSessionClientBase)tcpSession).Id;
        }
        /// <summary>
        ///数据解析
        /// </summary>
        /// <param name="between"></param>
        /// <returns></returns>
        public static RequestInfo DataAdapter(this BetweenAndRequestInfo between)
        {
            var body = new ReadOnlySequence<byte>(between.Body, 0, between.Body.Length);

            var keyindex = body.PositionOf(SpMark);
            if (!keyindex.HasValue)
            {
                ConsoleLogger.Default.Error($"头部要求违法");
            }
            var mainbody = body.Slice(keyindex.Value);
            var mainlen = mainbody.Length;
            var keygroup = DecodeKey(Encoding.UTF8.GetString(body.Slice(0, keyindex.Value)));
            var jsbody = Encoding.UTF8.GetString(mainbody.Slice(1, mainlen - 10));

            var sign = Encoding.UTF8.GetString(mainbody.Slice(mainlen - 8, 8));
            RequestInfo requestInfo = new RequestInfo(
            key: keygroup.Key,
            mid: keygroup.Mid,
            eventId: $"{keygroup.Key}{(string.IsNullOrEmpty(keygroup.Version) ? string.Empty : string.Format(":{0}", keygroup.Version))}",
           // messageId: string.IsNullOrEmpty(keygroup.Version) ? bodyext.Id : keygroup.CommandId,
            messageId: keygroup.CommandId,
            version: keygroup.Version,
            body: jsbody,
            sign: sign,
            clientId: between.ClientId
            );
            return requestInfo;
        }
        /// <summary>
        /// 
        /// </summary>
        /// <param name="keystring"></param>
        /// <returns></returns>
        /// <exception cref="Exception"></exception>
        private static KeyGroup DecodeKey(string keystring)
        {
            //var rs = new ();
            if (string.IsNullOrEmpty(keystring))
            {
                throw new Exception("连接已拒绝!");
            }
            var keylist = keystring.Split('-');

            if (keylist.Length > 4)
            {
                throw new Exception("错误的关键字串长度!");
            }
            if (keylist.Length == 4)
            {
                return new KeyGroup
                {
                    Key = keylist[0],
                    Mid = keylist[1],
                    CommandId = keylist[2],
                    Version = "V1",
                    ConvertType = 1 //keylist[3]
                };
            }
            else
            {
                return new KeyGroup
                {
                    Key = keylist[0],
                    Mid = "0000000000",
                    CommandId = string.Empty,
                    Version = string.Empty,
                    ConvertType = 1 //keylist[3]
                };
            }
        }
        #region 认证
        // 使用静态字典保存登录状态
        private readonly static DependencyProperty<bool> _isAuthProperty = new DependencyProperty<bool>(nameof(_isAuthProperty), false);

        public static bool GetAuth(this ITcpSession client)
        {
            if (client == null) throw new ArgumentNullException(nameof(client));
            return client.GetValue(_isAuthProperty);
        }
        /// <summary>
        /// 尝试获取认证状态。
        /// </summary>
        /// <param name="client">TCP会话客户端</param>
        /// <param name="value">获取到的认证状态值</param>
        /// <returns>是否成功获取到值</returns>
        public static bool TryGetAuth(this ITcpSession client, out bool value)
        {
            if (client == null) throw new ArgumentNullException(nameof(client));

            // 调用 TryGetValue 方法尝试获取依赖属性的值
            return client.TryGetValue(_isAuthProperty, out value);
        }
        public static void SetAuth(this ITcpSession client, bool value)
        {
            if (client == null) throw new ArgumentNullException(nameof(client));
            client.SetValue(_isAuthProperty, value);
        }
        public static void RemoveAuth(this ITcpSession client)
        {
            if (client == null) throw new ArgumentNullException(nameof(client));
            client.RemoveValue(_isAuthProperty);
        }
        #endregion

    }
}
